<?php

class mail extends Module {
	
	private static $aMessgaesTypes = null;
	
	public function __construct () {
		parent::__construct (__CLASS__);
		
		$this->extend ('__mail_comments');
		$this->extend ('__mail_mail');
		$this->extend ('__custom_mail');
	}
	
	public function __default () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		if (self::$aMessgaesTypes === null) {
			self::loadTypes ();
		}
		
		$sel = new Selection;
		
		foreach (self::$aMessgaesTypes as $typeId) {
			$sel->addType ($typesController->getTypeById ($typeId));
		}
		
		$sel->addFilter ('addressed_user_id', ExplaySession::getUserId ());
		$sel->addFilter ('sender_id', ExplaySession::getUserId ());
		$sel->setLogicOr ();
		$sel->setOrder ('date', false);
		
		$currentPage = getRequest ('page', 'int');
		if ($currentPage > 0) {
			$currentPage--;
		}

		$onPage = (int) Regedit::getInstance()->get ('//modules/mail/messages_on_page');
		
		if ($onPage == 0) {
			$onPage = 16; 
		}
		$sel->addLimit ($currentPage * $onPage, $onPage);
		
		$aObjects = $objectsController->getObjectsList($sel->getList ());
		
		$response = new ModuleResponse;
		
		$oTypeStatus = $typesController->getTypeByName ('message_status');
		
		foreach ($aObjects as $object) {
			$readSel = new Selection;
			$readSel->addType ($oTypeStatus);
			$readSel->addFilter ('message_id', $object->getId ());
			$readSel->addFilter ('type_id', $object->getType()->getId ());
			$readSel->addFilter ('user_id', ExplaySession::getUserId ());
			$readSel->addFilter ('read', '1');
			
			$object->setAttribute ('read', $readSel->getTotalCount () > 0 ? '1' : '0');
			
			$response->addObject ($object);
		}
		
		$response->addObject (new Array2XML ('pages', array (
			'onpage' => $onPage,
			'total' => $sel->getTotalCount (),
			'page' => ++$currentPage
		)));
		
		$response->setTemplate ('mail/index');
		
		return $response;
	}
	
	public function write () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$this->setPageTitle (lang ('module_header_write',__CLASS__));		
		
		$oMessageType = $typesController->getTypeByName ('message');
		
		$aErrors = array ();
		
		$form = new Form ($oMessageType, 'new');
		$form->buildFromType ();
		
		if (getRequest ('to', 'bool')) {
			$form->setValue ('addressed_user_id', getRequest ('to', 'int'));
		}
		
		if (getRequest ('param0') == 'send') {
			$aProperties = $this->getRequestData ('new', $oMessageType);
			
			$oMessage = new Object ($oMessageType);
			$oMessage->setValues ($aProperties);
			$oMessage->setValue ('date', time ());
			$oMessage->setValue ('sender_id', ExplaySession::getUserId ());
			
			$aErrors = $this->getValidateErrors ($oMessage, $oMessageType);
			
			if (!isset ($aErrors['addressed_user_id'])) {
				CMSController::getInstance()->loadModule('users'); // fix
				$aFriends = users::getUserFriends ();
				
				if (!in_array ($oMessage->getValue ('addressed_user_id'), $aFriends)) {
					$aErrors['addressed_user_id'] = lang ('error_not_such_friend',__CLASS__);
				}
			}
			
			if (count ($aErrors)) {
				$form->setErrors ($aErrors);
				$form->setValues ($aProperties);
			} else {
				$oMessage->createNew ();
				
				$oTypeStatus = $typesController->getTypeByName ('message_status');
				
				$oStatusSender = new Object ($oTypeStatus);
				$oStatusSender->setValues (array (
					'message_id' => $oMessage->getId (),
					'type_id' => $oMessageType->getId (),
					'user_id' => ExplaySession::getUserId (),
					'read' => '1'	
				));
				$oStatusSender->createNew ();
				
				$oStatusAddressed = new Object ($oTypeStatus);
				$oStatusAddressed->setValues (array (
					'message_id' => $oMessage->getId (),
					'type_id' => $oMessageType->getId (),
					'user_id' => $oMessage->getValue ('addressed_user_id'),
					'read' => '0'
				));
				$oStatusAddressed->createNew ();
				
				$this->messageNotification ($oMessage);
				
				redirect (HTTP_HOST . '/mail');
			}
		}
		
		$response = new ModuleResponse;
		$response->addObject ($form);
		$response->setTemplate ('mail/write');
		
		return $response;
	}
	
	public function read () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		$requestType = getRequest ('param0');
		$requestId = getRequest ('param1', 'int');
		
		if (!$oType = $typesController->getTypeByName ($requestType)) {
			throw new NotFound;
		}
		
		if (!self::validateType ($oType->getId ())) {
			throw new NotFound;
		}
		
		if (!$object = $objectsController->getObject ($oType, $requestId)) {
			throw new NotFound;
		}
		
		if ($object->getValue ('addressed_user_id') != ExplaySession::getUserId () && $object->getValue ('sender_id') != ExplaySession::getUserId ()) {
			throw new NotFound;
		}
		
		$this->setPageTitle ($object->getValue ('subject'));
		
		$oTypeStatus = $typesController->getTypeByName ('message_status');
		
		$readSel = new Selection;
		$readSel->addType ($oTypeStatus);
		$readSel->addFilter ('message_id', $requestId);
		$readSel->addFilter ('type_id', $oType->getId ());
		$readSel->addFilter ('user_id', ExplaySession::getUserId ());
		$readSel->addFilter ('read', '0');
		
		$res = $readSel->getList ();

		if (count ($res)) {
			$oRead = $objectsController->getObject ($oTypeStatus, $res[0][0]);
			$oRead->setValue ('read', '1');
			$oRead->save ();
		}
		
		$response = new ModuleResponse;
		$response->addObject ($object);
		$response->setTemplate ('mail/read');
		
		return $response;
	}
	
	public function delete () {
		$typesController = TypesController::getInstance ();
		$objectsController = ObjectsController::getInstance ();
		
		
		$oTypeStatus = $typesController->getTypeByName ('message_status');
		
		foreach ($_REQUEST['delete'] as $typeId => $aDeleteIds) {
			if (!self::validateType ($typeId) || !$oType = $typesController->getTypeById ($typeId)) {
				continue;
			}
			
			foreach ($aDeleteIds as $objectId) {
				if (!$object = $objectsController->getObject ($oType, $objectId)) {
					continue;
				}
				
				if ($object->getValue ('addressed_user_id') != ExplaySession::getUserId () && $object->getValue ('sender_id') != ExplaySession::getUserId ()) {
					continue;
				}
				
				$object->delete ();
				
				$selStatuses = new Selection;
				$selStatuses->addType ($oTypeStatus);
				$selStatuses->addFilter ('message_id', $objectId);
				$selStatuses->addFilter ('type_id', $typeId);
				
				$res = $selStatuses->getList ();
				
				foreach ($res as $row) {
					$objectsController->getObject($oTypeStatus, $row[0])->delete ();
				}
			}
		}
		redirect (HTTP_HOST . '/mail');
	}
		
	public function getCountNewMessages () {
		$sel = new Selection;
		$sel->addType (TypesController::getInstance()->getTypeByName ('message_status'));
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		$sel->addFilter ('read', '0');
		
		$response = new ModuleResponse;
		$response->addObject (new Array2XML ('count', array ($sel->getTotalCount ())));
		
		return $response;
	}
	
	public function getUserFriendsSelection ($selectedId = 0) {
		$oFriendType = TypesController::getInstance()->getTypeByName ('friend');
		$objectsController = ObjectsController::getInstance ();
		
		$sel = new Selection;
		$sel->addType ($oFriendType);
		$sel->addFilter ('user_id', ExplaySession::getUserId ());
		
		$aObjects = $objectsController->getObjectsList($sel->getList ());
		
		$response = new ModuleResponse;
		
		foreach ($aObjects as $object) {
			$object->setAttribute ('selected', $object->getValue ('friend_id') == $selectedId ? '1' : '0');
			
			$response->addObject ($object);
		}
		
		return $response;
	}
	
	public static function validateType ($typeId) {
		if (self::$aMessgaesTypes === null) {
			self::loadTypes ();
		}
		
		return in_array ($typeId, self::$aMessgaesTypes) ? true : false;
	}
	
	private static function loadTypes () {
		$sel = new Selection;
		$sel->addType (TypesController::getInstance()->getTypeByName ('message_type'));
		$sel->addSelectedProperty ('type_id');
		
		$res = $sel->getList ();
		self::$aMessgaesTypes = array ();
		
		foreach ($res as $row) {
			self::$aMessgaesTypes[] = $row['type_id'];
		}
	}
	
}